<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Seller\Controllers;


use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\Purchase;
use App\Eloquent\Ygt\ReturnPurchase;
use App\Eloquent\Ygt\ReturnPurchaseMaterial;
use App\Eloquent\Ygt\SellerCompany;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class PurchaseController extends Controller
{
    public $userId        = 25;
    public function index(){}
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        //$requestCompanyId   = request('company_id',0);
        //$sellerCompanyId    = request('seller_company_id',1);
        $from               = request('from',1);
        $fromId             = request('id',0);
        $page               = request('page',1);
        $limit              = request('limit',10);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $where              = [];
        switch ($from)
        {
            case 1:
                if(!$fromId )
                {
                    xThrow( ERR_PARAMETER,'请选择供应商' );
                }
                $where['id']    = $fromId;
                $companyId      = $userInfo->company_id;
                break;
            case 2:
                if(!$fromId)
                {
                    xThrow( ERR_PARAMETER,'请选择厂' );
                }
                $companyId              = $fromId;
                $where['user_id']       = $userId;
                $where['company_id']    = $companyId;
                break;
            default:
                xThrow( ERR_PARAMETER,'不是需要的类型' );
        }

        $sellerCompany      = SellerCompany::getInfo($where);
        if(!$sellerCompany)
        {
            xThrow( ERR_PARAMETER,'供应商信息出错' );
        }
        //取列表
        $sellerCompanyId    = $sellerCompany->id;
        $workflowStatusArr  = config('workflow.workflow_status');
        $sellerCompanyName  = $sellerCompany->title;
        $offset             = ($page-1)*$limit;
        $select             = 'ygt_purchase.id,ygt_purchase.purchase_number,ygt_purchase.application_cause';
        $select             .= ',ygt_purchase.content,ygt_purchase.created_at,ygt_purchase.finished_date,ygt_purchase.status';
        $select             .= ',oa_workflow.id as workflow_id';
        $select             .= ',oa_workflow.dispose_code';
        $query              = Purchase::query();
        $query              = $query->selectRaw($select);
        $query              = $query->join('oa_workflow', 'oa_workflow.related_id', '=', 'ygt_purchase.id');
        $query              = $query->where('oa_workflow.related_type','=',26);
        $query              = $query->where('ygt_purchase.supplier_id','=',$sellerCompanyId);
        $query              = $query->where('ygt_purchase.company_id','=',$companyId);
        if($from == 1)
        {
            $query          = $query->where('ygt_purchase.uid','=',$userId);
        }
        $query              = $query->orderByDesc('ygt_purchase.id');
        $collection         = $query->limit($limit)->offset($offset)->get();
        $lists              = $collection->toArray();
        //统计总条数
        $query              = Purchase::query();
        $query              = $query->where('supplier_id','=',$sellerCompanyId);
        $query              = $query->where('company_id','=',$companyId);
        if($from == 1)
        {
            $query          = $query->where('uid','=',$userId);
        }
        $count              = $query->count();
        $purchaseIdArr      = [];
        foreach($lists as $key=>$val)
        {
            $createdAtYmd   = date('Y-m-d',$val['created_at']);
            $lists[$key]['created_at']  = $createdAtYmd;
            $disposeCode    = $val['dispose_code'];
            $lists[$key]['status_name'] = isset($workflowStatusArr[$disposeCode]) ? $workflowStatusArr[$disposeCode] : '';
            $lists[$key]['img_path'] = '';
            $lists[$key]['product_name_str'] = '';
            $lists[$key]['application_cause'] = !empty($val['application_cause']) ? $val['application_cause'] : '';
            $lists[$key]['seller_company_name'] = $sellerCompanyName;
            $lists[$key]['purchase_number'] =  \App\Engine\Common::changeSnCode($val['purchase_number']);

            $purchaseIdArr[]            = $val['id'];
        }
        //取采购中相关材料的图片
        if(!empty($purchaseIdArr))
        {
            //取采购的图片,
            $join               = [
                ['table'=>'ygt_purchase_material', 'field_l'=>'ygt_purchase_material.material_id', 'field_c'=>'=', 'field_r'=>'ygt_product.id'],
            ];
            $columns            = 'ygt_purchase_material.purchase_id,ygt_product.img_id,ygt_product.product_name';
            $orderby            = ['ygt_purchase_material.id','desc'];
            $where              = ['ygt_purchase_material.purchase_id'=>['in',$purchaseIdArr]];
            $productList        = Product::getList($where,$columns,'','',$orderby,'',$join)->toArray();
            $imgIdArr           = [];
            foreach($productList as $key=>$val)
            {
                $imgIdArr[]     = $val['img_id'];
            }
            $where              = ['id'=>['in',$imgIdArr]];
            $imgList            = ImgUpload::getList($where)->toArray();
            $imgPathArr         = [];
            foreach($imgList as $key=>$val)
            {
                $imgPath        = Func::getImgUrlHttp($val['img_url']);
                $imgPathArr[$val['id']]     = $imgPath;
            }
            foreach($productList as $key=>$val)
            {
                $imgId          = $val['img_id'];
                $imgPath        = isset($imgPathArr[$imgId]) ? $imgPathArr[$imgId] : '';
                $productList[$key]['img_path']  = $imgPath;
            }


            //统计采购单总金额
            $purchasePriceList = [];
            $tmpPurchaseMaterialList = \App\Eloquent\Ygt\PurchaseMaterial::whereIn('purchase_id',$purchaseIdArr)->get();
            foreach ($tmpPurchaseMaterialList as $tmpPurchaseMaterialRow){
                if(isset($purchasePriceList[$tmpPurchaseMaterialRow['purchase_id']])){
                    $purchasePriceList[$tmpPurchaseMaterialRow['purchase_id']] += $tmpPurchaseMaterialRow['price']*$tmpPurchaseMaterialRow['num'];
                }else{
                    $purchasePriceList[$tmpPurchaseMaterialRow['purchase_id']] = $tmpPurchaseMaterialRow['price']*$tmpPurchaseMaterialRow['num'];
                }
            }


            foreach($lists as $key=>$val)
            {
                $productNameStr = $imgPath = '';
                $productNameArr = [];
                foreach($productList as $k=>$v)
                {
                    if($val['id'] == $v['purchase_id'])
                    {
                        $imgPath            = $val['img_path'];
                        $productNameArr[]   = $v['product_name'];
                    }
                }
                $productNameStr     = implode(',',$productNameArr);
                $lists[$key]['img_path']          = $imgPath;
                $lists[$key]['product_name_str'] = $productNameStr;

                foreach ($purchasePriceList as $tmpPurchaseId => $tmpPurchasePrice){
                    if($val['id'] == $tmpPurchaseId){
                        $lists[$key]['all_price'] = $tmpPurchasePrice;
                        $lists[$key]['all_price'] = '¥'.sprintf("%.2f",$lists[$key]['all_price']);
                    }
                }
            }
        }
        //return $lists;
        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($lists, $pagingData);
    }
    public function backList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $from               = request('from',1);
        $fromId             = request('id',0);
        $page               = request('page',1);
        $limit              = request('limit',10);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $where              = [];
        switch ($from)
        {
            case 1:
                if(!$fromId )
                {
                    xThrow( ERR_PARAMETER,'请选择供应商' );
                }
                $where['id']    = $fromId;
                $companyId      = $userInfo->company_id;
                break;
            case 2:
                if(!$fromId)
                {
                    xThrow( ERR_PARAMETER,'请选择厂' );
                }
                $companyId              = $fromId;
                $where['user_id']       = $userId;
                $where['company_id']    = $companyId;
                break;
            default:
                xThrow( ERR_PARAMETER,'不是需要的类型' );
        }

        $sellerCompany      = SellerCompany::getInfo($where);
        if(!$sellerCompany)
        {
            xThrow( ERR_PARAMETER,'供应商信息出错' );
        }
        //取列表
        $sellerCompanyId    = $sellerCompany->id;
        $workflowStatusArr  = config('workflow.workflow_status');
        $sellerCompanyName  = $sellerCompany->title;
        $offset             = ($page-1)*$limit;
        $select             = 'ygt_return_purchase.id,ygt_return_purchase.purchase_number';
        $select             .= ',ygt_return_purchase.content,ygt_return_purchase.created_at';
        $select             .= ',ygt_return_purchase.payment_method,ygt_return_purchase.status';
        $select             .= ',oa_workflow.id as workflow_id';
        $select             .= ',oa_workflow.dispose_code';
        $query              = ReturnPurchase::query();
        $query              = $query->selectRaw($select);
        $query              = $query->join('oa_workflow', 'oa_workflow.related_id', '=', 'ygt_return_purchase.id');
        $query              = $query->where('oa_workflow.related_type','=',27);
        $query              = $query->where('oa_workflow.dispose_code','=',1100);
        //$query              = $query->where('ygt_return_purchase.supplier_id','=',1);//先按照写死走
        $query              = $query->where('ygt_return_purchase.supplier_id','=',$sellerCompanyId);
        $query              = $query->where('ygt_return_purchase.company_id','=',$companyId);
        if($from == 1)
        {
            $query          = $query->where('ygt_return_purchase.uid','=',$userId);
        }
        $query              = $query->orderByDesc('ygt_return_purchase.id');
        $collection         = $query->limit($limit)->offset($offset)->get();
        $lists              = $collection->toArray();
        //统计总条数
        $query              = ReturnPurchase::query();
        //$query              = $query->where('supplier_id','=',1);//先按照写死走
        $query              = $query->where('supplier_id','=',$sellerCompanyId);
        $query              = $query->where('company_id','=',$companyId);
        if($from == 1)
        {
            $query          = $query->where('uid','=',$userId);
        }
        $count              = $query->count();
        $purchaseIdArr      = [];
        foreach($lists as $key=>$val)
        {
            $createdAtYmd   = date('Y-m-d',$val['created_at']);
            $lists[$key]['created_at']  = $createdAtYmd;
            $lists[$key]['finished_date']  = '';
            $disposeCode    = $val['dispose_code'];
            $lists[$key]['status_name'] = isset($workflowStatusArr[$disposeCode]) ? $workflowStatusArr[$disposeCode] : '';
            $lists[$key]['img_path'] = '';
            $lists[$key]['product_name_str'] = '';
            $lists[$key]['application_cause'] = !empty($val['application_cause']) ? $val['application_cause'] : '';
            $lists[$key]['seller_company_name'] = $sellerCompanyName;
            $lists[$key]['purchase_number'] =  \App\Engine\Common::changeSnCode($val['purchase_number']);

            $purchaseIdArr[]            = $val['id'];
        }
        //取采购中相关材料的图片
        if(!empty($purchaseIdArr))
        {
            //取采购的图片,
            $join               = [
                ['table'=>'ygt_return_purchase_material', 'field_l'=>'ygt_return_purchase_material.material_id', 'field_c'=>'=', 'field_r'=>'ygt_product.id'],
            ];
            $columns            = 'ygt_return_purchase_material.purchase_id,ygt_product.img_id,ygt_product.product_name';
            $orderby            = ['ygt_return_purchase_material.id','desc'];
            $where              = ['ygt_return_purchase_material.purchase_id'=>['in',$purchaseIdArr]];
            $productList        = Product::getList($where,$columns,'','',$orderby,'',$join)->toArray();
            $imgIdArr           = [];
            foreach($productList as $key=>$val)
            {
                $imgIdArr[]     = $val['img_id'];
            }
            $where              = ['id'=>['in',$imgIdArr]];
            $imgList            = ImgUpload::getList($where)->toArray();
            $imgPathArr         = [];
            foreach($imgList as $key=>$val)
            {
                $imgPath        = Func::getImgUrlHttp($val['img_url']);
                $imgPathArr[$val['id']]     = $imgPath;
            }
            foreach($productList as $key=>$val)
            {
                $imgId          = $val['img_id'];
                $imgPath        = isset($imgPathArr[$imgId]) ? $imgPathArr[$imgId] : '';
                $productList[$key]['img_path']  = $imgPath;
            }
            foreach($lists as $key=>$val)
            {
                $productNameStr = $imgPath = '';
                $productNameArr = [];
                foreach($productList as $k=>$v)
                {
                    if($val['id'] == $v['purchase_id'])
                    {
                        $imgPath            = $val['img_path'];
                        $productNameArr[]   = $v['product_name'];
                    }
                }
                $productNameStr     = implode(',',$productNameArr);
                $lists[$key]['img_path']          = $imgPath;
                $lists[$key]['product_name_str'] = $productNameStr;
            }
        }
        //return $lists;
        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($lists, $pagingData);
    }
    public function backDetail()
    {
        $userId             = Func::getHeaderValueByName('userid',256);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $requestId          = request('id',0);
        if(!$userInfo || !$requestId)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $where              = ['id'=>$requestId];
        $info               = ReturnPurchase::where($where)->first();
        if(!$info)
        {
            xThrow( ERR_PARAMETER,'退货信息出错' );
        }
        $purchase           = $info->toArray();
        $purchaseId         = $purchase['id'];
        //取退货单材料信息
        $where              = ['purchase_id'=>$purchaseId];
        $materialList       = ReturnPurchaseMaterial::where($where)->get()->toArray();
        $productIdArr       = [];
        foreach($materialList as $key=>$val)
        {
            $productIdArr[] = $val['material_id'];
        }
        //取列表
        $where              = ['ygt_product.id'=>['in',$productIdArr]];
        $productList        = Product::getListByJoin($where,'')->toArray();
        //取材料的自定义属性值
        $where              = ['product_id'=>['in',$productIdArr]];
        $customFieldsArr    = ProductFields::getTransformListToArr($where);
        //转换列表
        $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
        $productList        = Product::transformListByType($productList,$otherArr);
        foreach($productList as $key=>$val)
        {
            $number         = $price = 0;
            foreach($materialList as $k=>$v)
            {
                if($val['id'] == $v['material_id'])
                {
                    $number     = $v['num'];
                    $price      = $v['price'];
                }
            }
            $productList[$key]['number']    = $number;
            $productList[$key]['price']     = $price;
        }
        $result             = [
            'purchase'=>$purchase,
            'product_list'=>$productList,
        ];
        return $result;
    }

}